package com.reading.cms.framework.shiro.filter.captcha;

import com.google.code.kaptcha.Constants;
import com.reading.cms.framework.constant.ShiroConstants;
import com.reading.cms.utils.ShiroUtil;
import com.reading.common.utils.StringUtil;
import lombok.Setter;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 短信验证码过滤器
 *
 * @author ruoyi
 */
@Setter
public class SmsCodeValidateFilter extends AccessControlFilter {

    /**
     * 是否开启验证码
     */
    private boolean smsCodeEbabled = true;

    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        request.setAttribute(ShiroConstants.CURRENT_EBABLED, smsCodeEbabled);
        return super.onPreHandle(request, response, mappedValue);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
        throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 验证码禁用 或不是表单提交 允许访问
        if (!smsCodeEbabled || !"post".equals(httpServletRequest.getMethod().toLowerCase())) {
            return true;
        }
        return validateResponse(httpServletRequest, httpServletRequest.getParameter("smsValidateCode"));
    }

    public boolean validateResponse(HttpServletRequest request, String validateCode) {
        Object obj = ShiroUtil.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        String code = String.valueOf(obj != null ? obj : "");
        if (StringUtil.isEmpty(validateCode) || !validateCode.equalsIgnoreCase(code.split(",")[0])) {
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        request.setAttribute(ShiroConstants.CURRENT_CAPTCHA_SMS, ShiroConstants.CAPTCHA_ERROR);
        return true;
    }
}
